//
//  MyShareViewController.m
//  phmall
//
//  Created by admin on 2017/12/9.
//  Copyright © 2017年 admin. All rights reserved.
//

#import "MyShareViewController.h"
#import "MyShareViewCell.h"

#import "ShareModel.h"
@interface MyShareViewController ()<UITableViewDelegate,UITableViewDataSource,MyShareViewCellDelegate,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>
@property(strong,nonatomic)UITableView *myTableview;
@property(strong,nonatomic)NSMutableArray *myShare;
@property(nonatomic,strong)MBProgressHUD *hud;
@end

@implementation MyShareViewController
-(void)removeAction:(UITableViewCell *)cell{
    NSIndexPath *index=[self.myTableview indexPathForCell:cell];
    ShareModel *model=self.myShare[index.section];
    
    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"myshare/del"];
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    [parametersDic setValue:model.uid forKey:@"uid"];
    [httpTool ZBPostNetDataWith:urlstr withDic:parametersDic andSuccess:^(id responseObject) {
        NSMutableDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([responseDict[@"ret"] isEqualToString:@"200"]) {
            if ([[NSString stringWithFormat:@"%@",responseDict[@"data"][@"status"]] isEqualToString:@"1"]) {
                [PublicClass ProgressHUDModeText:Localized(@"删除成功") andTime:2];
                [self loadMyShare:YES];
            }
        }
    } andFailure:^{
//        if (self.emptyType==EmptyDataSetNoNetwork) {
            [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2];
//        }
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"我的分享";
    UIBarButtonItem* leftBar=[[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"返回"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(leftBarAction)];
    self.navigationItem.leftBarButtonItem=leftBar;
    
    [self.view addSubview:self.myTableview];
    [self.myTableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(0);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view).with.offset(self.tabBar_height);
    }];
    [self loadMyShare:YES];
    
    if (@available(iOS 11.0, *)) {
        self.myTableview.estimatedRowHeight = 0;
        self.myTableview.estimatedSectionFooterHeight = 0;
        self.myTableview.estimatedSectionHeaderHeight = 0;
        self.myTableview.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }

//    self.myTableview.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footeRefresh)];
//    self.myTableview.mj_footer.hidden=YES;
    self.myTableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(HeaderRefresh)];
    // Do any additional setup after loading the view.
}
-(void)HeaderRefresh{
    [self loadMyShare:NO];
}
- (void)loadMyShare:(BOOL)reload{
    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"myshare"];
    [httpTool ZBPostNetDataWith:urlstr withDic:nil andSuccess:^(id responseObject) {
        [self.myShare removeAllObjects];
        self.emptyType=EmptyDataSetNoData;
        NSMutableDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if (responseDict[@"data"] !=[NSNull alloc]) {
            NSMutableArray *data=responseDict[@"data"];
            if (data.count==0) {
                [self.myTableview.mj_header endRefreshing];
                [self.myTableview.mj_footer endRefreshingWithNoMoreData];
                if (reload) {
                    [self.myTableview reloadData];
                }
            }else{
                [self analysisDataWithNewArray:data];
            }
        }
        [self.hud hideAnimated:YES];
    } andFailure:^{
        [self.hud hideAnimated:YES];
        if (self.emptyType==EmptyDataSetNoNetwork) {
            [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2 ];
        }
        [self.myShare removeAllObjects];
        self.emptyType=EmptyDataSetNoNetwork;
        [self.myTableview reloadData];
        [self.myTableview.mj_header endRefreshing];
    }];
}
- (void)analysisDataWithNewArray:(NSMutableArray *)array{
    for (NSDictionary *dict in array)
    {
        ShareModel *model = [ShareModel yy_modelWithDictionary:dict];
        [self.myShare addObject:model];
    }

    [self.myTableview reloadData];
    [self.myTableview.mj_header endRefreshing];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 170;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.myShare.count;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    //总高度
    if (section==0) {
        return 10;
    }else{
        return 0.01;
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MyShareViewCell *cell=[MyShareViewCell theShareCellWithTableView:tableView];
    ShareModel *model=self.myShare[indexPath.row];
    cell.model=model;
    cell.delegate=self;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    //分割线补全
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}

#pragma mark  DZNEmptyDataSetDelegate
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    switch (self.emptyType) {
        case EmptyDataSetNone:
            return nil;
            break;
        case EmptyDataSetNoData:
            
            return [UIImage imageNamed:@"订单缺失"];
            break;
        case EmptyDataSetNoNetwork:
            
            return [UIImage imageNamed:@"断网"];
            break;
    }
}


- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView{
    
    switch (self.emptyType) {
        case EmptyDataSetNone:
            return NO;
            break;
        case EmptyDataSetNoData:
            return YES;
            break;
        case EmptyDataSetNoNetwork:
            return NO;
            break;
    }
    return YES;
}
- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
    return 0;
}
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    
    if (self.emptyType==EmptyDataSetNoData) {
        NSMutableAttributedString *currentPriceStr = [[NSMutableAttributedString alloc] initWithString:@"您的购物车是空的哦！\n跟我去采一些吧。"];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:20],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#E6963F"]} range:NSMakeRange(0, 10)];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:18],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#C2AA93"]} range:NSMakeRange(10, 9)];
        return currentPriceStr;
    }
    if (self.emptyType==EmptyDataSetNoNetwork){
        NSMutableAttributedString *currentPriceStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\n%@",Localized(@"您的网络不给力啊!"),Localized(@"请您检查是否联网。")]];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:22],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#E6963F"]} range:NSMakeRange(0, [Localized(@"您的网络不给力啊!") length])];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:18],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#C2AA93"]} range:NSMakeRange([Localized(@"您的网络不给力啊!") length], [Localized(@"请您检查是否联网。") length])];
        return currentPriceStr;
    }
    return nil;
}
- (NSAttributedString *)buttonTitleForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state {
    
    if (self.emptyType==EmptyDataSetNoNetwork){
        NSMutableAttributedString *currentPriceStr = [[NSMutableAttributedString alloc] initWithString:Localized(@"重新加载")];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:18],NSForegroundColorAttributeName:[UIColor whiteColor]} range:NSMakeRange(0, [Localized(@"重新加载") length])];
        return currentPriceStr;
    }else{
        return nil;
    }
    
}
#pragma mark - DZNEmptyDataSetDelegate

- (void)emptyDataSet:(UIScrollView *)scrollView didTapButton:(UIButton *)button {
    [self loadMyShare:YES];
    self.hud=[MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow  animated:YES];
    self.hud.detailsLabel.text =  Localized(@"加载中...");
}

- (void)emptyDataSetWillAppear:(UIScrollView *)scrollView {
    self.myTableview.contentOffset = CGPointZero;
}

//MARK:-GETTER
- (UITableView *)myTableview{
    if (!_myTableview) {
        _myTableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _myTableview.delegate = self;
        _myTableview.dataSource = self;
        _myTableview.backgroundColor=[UIColor groupTableViewBackgroundColor];
        _myTableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _myTableview.showsVerticalScrollIndicator=NO;
        _myTableview.scrollEnabled = YES;
        _myTableview.emptyDataSetSource = self;
        _myTableview.emptyDataSetDelegate = self;
    }
    return _myTableview;
}

-(NSMutableArray *)myShare{
    if (!_myShare) {
        _myShare=[[NSMutableArray alloc]init];
    }
    return _myShare;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
